//
// Created by Administrator on 2020/3/3 0003.
//

#include "log.h"
#include <jni.h>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <queue>

using namespace std;

std::queue<int> data;
pthread_mutex_t mutex;  /*互斥变量*/
pthread_cond_t cond; /*条件变量*/
pthread_t waitHandle;
pthread_t notifyHandle;


void *producterThread(void *args) {
    LOGD("生产线程");
    while (data.size() < 10) {
        pthread_mutex_lock(&mutex);
        data.push(1);
        if (data.size() > 0) {
            LOGD("生产线程 等待消费");
            pthread_cond_signal(&cond);
        }
        pthread_mutex_unlock(&mutex);
        sleep(3);
    }
    pthread_exit(0);
}

void *consumerThread(void *args) {
    LOGI("消费线程 ");
    while (1) {
        pthread_mutex_lock(&mutex);
        if (data.size() > 0) {
            LOGI("消费线程 消费物品");
            data.pop();
        } else {
            LOGI("消费线程 等待生产");
            pthread_cond_wait(&cond, &mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_hrg_gys_clfr_myapplication_JniData_syncThread1(JNIEnv *env, jclass clazz) {
    // TODO: implement syncThread1()
    pthread_mutex_init(&mutex, nullptr);
    pthread_cond_init(&cond, nullptr);
    pthread_create(&waitHandle, NULL, producterThread, NULL);
}

extern "C"
JNIEXPORT void JNICALL
Java_com_hrg_gys_clfr_myapplication_JniData_syncThread2(JNIEnv *env, jclass clazz) {
    // TODO: implement syncThread2()
    pthread_create(&notifyHandle, NULL, consumerThread, NULL);
}
